package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 * Created by 16060457 on 2017/11/8.
 */
public class IocHelper {

    static {
        // 获取到所有bean的类和实例的映射集合
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (CollectionUtil.isNotEmpty(beanMap)){
            // 遍历beanMap
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                Class<?> cls = beanEntry.getKey();
                Object obj = beanEntry.getValue();
                // 获取该bean的全部成员变量
                Field[] beanFields = cls.getDeclaredFields();
                if (ArrayUtil.isNotEmpty(beanFields)) {
                    for (Field field : beanFields) {
                        // 判断是否是需要依赖注入的成员变量
                        if (field.isAnnotationPresent(Inject.class)) {
                            Class<?> fieldTypeClass = field.getType();
                            // 获取该变量类型对应的实例
                            Object fieldInstance = beanMap.get(fieldTypeClass);
                            if (fieldInstance != null) {
                                // 通过反射注入成员变量的值
                                ReflectionUtil.setField(obj, field, fieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }

}
